package com.begye.smartloan.apptest.renzheng.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.ext.isUrl
import org.json.JSONObject

class FillItemBangKaListDialogAdapter(
    var dataList: List<JSONObject>,
    var clickAction: (Int, JSONObject) -> Unit
) :
    RecyclerView.Adapter<FillItemBangKaListDialogAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item_fill_item_bang_ka_list_dialog, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val listItemFillItemBangKaListDialogTitle: TextView =
            view.findViewById(R.id.listItemFillItemBangKaListDialogTitle)
        private val listItemFillItemBangKaListDialogIcon: ImageView =
            view.findViewById(R.id.listItemFillItemBangKaListDialogIcon)
        private val listItemFillItemBangKaListDialogCheckedIcon: ImageView =
            view.findViewById(R.id.listItemFillItemBangKaListDialogCheckedIcon)

        fun bindData(position: Int, item: JSONObject) {
            listItemFillItemBangKaListDialogTitle.text = item.optString("title", "")

            val checked = item.optBoolean("checked", false)
            if (checked) {
                listItemFillItemBangKaListDialogCheckedIcon.visibility = View.VISIBLE
            } else {
                listItemFillItemBangKaListDialogCheckedIcon.visibility = View.INVISIBLE
            }

            val logo = item.optString("logo", "")
            if (logo.isUrl()) {
                Glide.with(listItemFillItemBangKaListDialogIcon).load(logo)
                    .into(listItemFillItemBangKaListDialogIcon)
            }

            listItemFillItemBangKaListDialogTitle.setOnClickListener {
                clickAction.invoke(position, item)
            }

            listItemFillItemBangKaListDialogIcon.setOnClickListener {
                clickAction.invoke(position, item)
            }

            listItemFillItemBangKaListDialogCheckedIcon.setOnClickListener {
                clickAction.invoke(position, item)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(position, dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}